package com.szml.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.szml.context.BaseContext;
import com.szml.vo.LoginVO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.szml.constants.RedisConstants.LOGIN_USER_KEY;
import static com.szml.constants.RedisConstants.LOGIN_USER_TTL;

public class RefreshTokenInterceptor implements HandlerInterceptor {
    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求头中的token
        String token = request.getHeader("authorization");
        if (StrUtil.isBlank(token)) {
            response.setStatus(401);
        }
        //2获取redis中的user对象
        Map<Object, Object> loginVOMap = stringRedisTemplate.opsForHash().entries(LOGIN_USER_KEY + token);
        //3判断用户是否存在
        if (loginVOMap.isEmpty()) {

            response.setStatus(401);
        }
        //将hash对象转换成user对象
        LoginVO loginVO = BeanUtil.fillBeanWithMap(loginVOMap, new LoginVO(), false);
        //5.存在保存用户信息到ThreadLocal
        BaseContext.saveUser(loginVO);

        //刷新token有效期
        stringRedisTemplate.expire(LOGIN_USER_KEY + token, LOGIN_USER_TTL, TimeUnit.MINUTES);
        //6放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContext.removeLoginVO();
    }
}
